package com.dy.设计问题.打乱数组;

import java.util.Random;

/*
Shuffle an Array
打乱一个没有重复元素的数组。

示例:

// 以数字集合 1, 2 和 3 初始化数组。
int[] nums = {1,2,3};
Solution solution = new Solution(nums);

// 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。
solution.shuffle();

// 重设数组到它的初始状态[1,2,3]。
solution.reset();

// 随机返回数组[1,2,3]打乱后的结果。
solution.shuffle();
 */
public class Solution {
    int[] nums;
    int[] copy;
    public Solution(int[] nums) {
        this.nums = new int[nums.length];
        this.copy = nums;
        System.arraycopy(nums,0,this.nums,0,nums.length);
    }

    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return this.nums;

    }

    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        Random random = new Random();

        for(int i =0;i<copy.length;i++){
            int j =random.nextInt(copy.length); //不对，概率不等
            int tmp = copy[i];
            copy[i] = copy[j];
            copy[j] = tmp;
        }
        return copy;
    }
    public int[] shuffle2() {
        int rightEnd = copy.length -1;
        Random random = new Random();

        int r;
        while (rightEnd >0)
        {
            r = random.nextInt(rightEnd + 1);
            if(r != rightEnd)
                swap(copy,r,rightEnd);
            rightEnd--;
        }
        return copy;
    }
    private void swap(int[] array, int i, int j)
    {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}
